package org.jeecg.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.collections.CollectionUtils;
import org.jeecg.modules.entity.DbCusFollowUp;
import org.jeecg.modules.entity.DbCustomer;
import org.jeecg.modules.entity.vo.CusStatisticsVo;
import org.jeecg.modules.entity.vo.CusCountVo;
import org.jeecg.modules.mapper.DbCustomerMapper;
import org.jeecg.modules.service.IDbCusFollowUpService;
import org.jeecg.modules.service.IDbCustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: db_customer
 * @Author: jeecg-boot
 * @Date:   2024-06-13
 * @Version: V1.0
 */
@Service
public class DbCustomerServiceImpl extends ServiceImpl<DbCustomerMapper, DbCustomer> implements IDbCustomerService {

    @Autowired
    private DbCustomerMapper dbCustomerMapper;
    @Autowired
    @Lazy
    private IDbCusFollowUpService dbCusFollowUpService;
    /**
     * 查询客户名称列表
     * @return
     */
    @Override
    public List<String> getCusNameList() {
        List<DbCustomer> list = this.list();
        ArrayList<String> nameList = new ArrayList<>();
        if(nameList!=null){
            list.forEach(item->{
                nameList.add(item.getName());
            });
            return nameList;
        }
       return null;
    }

    /**
     * 客户统计
     * @param type
     * @return
     */
    @Override
    public CusCountVo cusCount(Integer type) {
        if(type==0){
            return cusTierCount();
        }else if(type==1){
            return cusIndustryCount();
        }else if(type==2){
            return cusProvinceCount();
        }else if (type==3){
            return cusCityCount();
        }
        else {
            return null;
        }
    }
    /**
     * 客户数量统计
     * @return
     */
    @Override
    public CusStatisticsVo cusStatistics() {
//       统计客户总数
        Long total = dbCustomerMapper.selectCount(Wrappers.emptyWrapper());
//        统计本月新增
        QueryWrapper<DbCustomer> wrapper = new QueryWrapper<>();
        LocalDate now = LocalDate.now();
        // 获取当前月份的第一天（月初）
        LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        // 获取当前月份的最后一天（月底）
        LocalDate lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
        wrapper.ge("create_time",firstDayOfMonth)
                .le("create_time",lastDayOfMonth);
        Long increase = dbCustomerMapper.selectCount(wrapper);
        LocalDate localDate = now.minusDays(30);
//        查询所有customerId
        List<DbCustomer> dbCustomers = dbCustomerMapper.selectList(Wrappers.emptyWrapper());
        List<String > ids = null;
        if(CollectionUtils.isNotEmpty(dbCustomers)){
            ids = dbCustomers.stream()
                    .map(dbCustomer -> dbCustomer.getId())
                    .collect(Collectors.toList());
        }
        LambdaQueryWrapper<DbCusFollowUp> wrappers = Wrappers.<DbCusFollowUp>lambdaQuery().in(DbCusFollowUp::getCusId, ids)
                .orderByDesc(DbCusFollowUp::getDate)
                .last("LIMIT 1");
        List<DbCusFollowUp> dbCusFollowUpList = dbCusFollowUpService.list(wrappers);
        List<DbCusFollowUp> ups = null;
        if(CollectionUtils.isNotEmpty(dbCusFollowUpList)){
            ups = dbCusFollowUpList.stream()
                    .filter(dbCusFollowUp -> dbCusFollowUp.getDate().isBefore(localDate))
                    .collect(Collectors.toList());
        }
        long followUp = ups.stream().count();
        return CusStatisticsVo.builder().total(total).increase(increase).followUp(followUp).build();
    }

    /**
     * 客户级别统计
     * @return
     */
    private CusCountVo cusTierCount() {
        CusCountVo cusCountVo = new CusCountVo();
        QueryWrapper<DbCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("tier,count(*) as total").groupBy("tier");
        List<Map<String, Object>> maps = this.listMaps(queryWrapper);
        if(maps==null){
            return null;
        }
        ArrayList<String> names = new ArrayList<>();
        ArrayList<Long> values = new ArrayList<>();
        for (Map<String, Object> map : maps) {
            names.add(map.get("tier").toString());
            values.add((Long)map.get("total"));
        }
        cusCountVo.setNameList(names);
        cusCountVo.setValueList(values);
        return cusCountVo;
    }
    /**
     * 客户行业统计
     * @return
     */
    private CusCountVo cusIndustryCount() {
        CusCountVo cusCountVo = new CusCountVo();
        QueryWrapper<DbCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("industry,count(*) as total").groupBy("industry");
        List<Map<String, Object>> maps = this.listMaps(queryWrapper);
        if(maps==null){
            return null;
        }
        ArrayList<String> names = new ArrayList<>();
        ArrayList<Long> values = new ArrayList<>();
        for (Map<String, Object> map : maps) {
            names.add(map.get("industry").toString());
            values.add((Long)map.get("total"));
        }
        cusCountVo.setNameList(names);
        cusCountVo.setValueList(values);
        return cusCountVo;
    }
    /**
     * 客户地区统计(省级)
     * @return
     */
    private CusCountVo cusProvinceCount() {
        CusCountVo cusCountVo = new CusCountVo();
        List<HashMap> list =dbCustomerMapper.getProvinceCount();
        if(list==null){
            return null;
        }
        ArrayList<String> names = new ArrayList<>();
        ArrayList<Long> values = new ArrayList<>();
        for (HashMap hashMap : list) {
            names.add(hashMap.get("province").toString());
            values.add((Long)hashMap.get("total"));
        }
        cusCountVo.setNameList(names);
        cusCountVo.setValueList(values);
        return cusCountVo;
    }
    /**
     * 客户地区统计(市级)
     * @return
     */
    private CusCountVo cusCityCount() {
        CusCountVo cusCountVo = new CusCountVo();
        List<HashMap> list =dbCustomerMapper.getCityCount();
        if(list==null){
            return null;
        }
        ArrayList<String> names = new ArrayList<>();
        ArrayList<Long> values = new ArrayList<>();
        for (HashMap hashMap : list) {
            names.add(hashMap.get("city").toString());
            values.add((Long)hashMap.get("total"));
        }
        cusCountVo.setNameList(names);
        cusCountVo.setValueList(values);
        return cusCountVo;
    }
}
